import re

def parse_unit(f):
    pat = re.compile(r'([01x]{32})\s+(\w+)')
    encoding_list = []
    line_num = 0
    for line in f:
        line_num += 1
        if line == '\n':
            continue
        match = pat.match(line)
        bitpat, name = match.group(1, 2)
        encoding_list.append((bitpat, name, line_num))
    return encoding_list

def overlap(bitpat1, bitpat2):
    for bit1, bit2 in zip(bitpat1, bitpat2):
        if bit1 == '1' and bit2 == '0' or bit1 == '0' and bit2 == '1':
            return False
    return True

# returns list of pairs overlapping encodings
def check_overlap(encoding_list):
    overlapping_pair_list = []
    n = len(encoding_list)
    for i in range(n):
        for j in range(i+1, n):
            enc1 = encoding_list[i]
            enc2 = encoding_list[j]
            if overlap(enc1[0], enc2[0]):
                overlapping_pair_list.append((enc1, enc2))
    return overlapping_pair_list

def parse_file(path):
    error = False
    with open(path, 'r') as f:
        encoding_list = parse_unit(f)
        overlapping_pair_list = check_overlap(encoding_list)
        if overlapping_pair_list:
            error = True
            for enc1, enc2 in overlapping_pair_list:
                print('%s: patterns at line %d and %d overlap' % (path, enc1[2], enc2[2]), file=sys.stderr)
    if error:
        return None
    return encoding_list
